import { useModelStore } from '@app-nextmesh/store/model';
import { useProjectStore } from '@app-nextmesh/store/project';
import { ENTITY_TYPES, ModelEventType, ModelTheme } from '@app-nextmesh/types';
import { events } from '@app-nextmesh/utils';
import { useEffect, useState } from 'react';
import NativeSelect from './NativeSelect';
import { ISelectProps } from './types';

export default function GeometriesSetSelect(props: ISelectProps) {
  const geometries = useProjectStore((state) => state.projectInfo?.geometries);
  const [value, setValue] = useState<string[]>([]);
  // 模型是否加载完成
  const modelLoaded = useModelStore((state) => state.loaded);
  const modelTheme = ModelTheme.Source;
  useEffect(() => {
    setValue([]);
    const values = props.value as string[];
    setValue(values);
    if (!modelLoaded) {
      return;
    }
    selectIndices(values); // TODO 应该设置geometry的objects选中（高亮）
  }, [props.value, modelLoaded]);
  useEffect(() => {
    return () => {
      // 清除选中状态等
      events.emit(ModelEventType.SetPicked, {
        indices: [],
        theme: modelTheme,
      });
      events.emit(ModelEventType.PickTypes, { types: ENTITY_TYPES });
      events.emit(ModelEventType.SwitchTheme, ModelTheme.Default);
    };
  }, [value]);

  const selectIndices = (values: string[]) => {
    const indices: string[] = [];
    geometries?.forEach((item) => {
      if (values) {
        if (values.includes(item?.name) && item?.objects?.length > 0) {
          indices.push(...item.objects);
        }
      }
    });
    // 获取选中的elementSets
    events.emit(ModelEventType.SetPicked, {
      indices,
      theme: modelTheme,
    });
  };
  const handleInputChange = (value: string | number | string[]) => {
    const values = value as string[];
    props.onChange(values);
    setValue(values);
    selectIndices(values);
  };

  const options =
    geometries?.map((item) => {
      return { label: item.name, value: item.name };
    }) ?? [];

  return (
    <NativeSelect
      value={value}
      onChange={(value) => handleInputChange(value)}
      options={options}
      disabled={props.disabled}
      multiple={true}
    />
  );
}
